<?php

/**
 * 前端盒子相关接口
 */

namespace app\api\controller;

use app\common\controller\Common;
use think\Db;

class Front extends Common
{
    //设置权限验证
    public function _initialize()
    {
        parent::_initialize();
        // //首先判断请求接口是否为登录或者检查权限，如果是则跳过权限验证
        // $request = Request::instance();
        // if ($request->action() != "checkStatusByMac" && $request->action() != "typeLogin") {
        //     $param = Request::instance()->param();
        //     $authKey = $param['token'];
        //     $cache = cache('Front_' . $authKey);
        //     // 校验sessionid和authKey
        //     if (empty($authKey) || empty($cache) || !$cache || cache('person_' . $cache['userInfo']['id']) != $authKey) {
        //         cache('Front_' . $authKey, null);
        //         header('Content-Type:application/json; charset=utf-8');
        //         exit(json_encode(['code' => 400, 'error' => '登录已失效']));
        //     }
        //     //获取需要检查的mac地址,并且检查mac地址是否在授权缓存中
        //     // $mac = $cache['mac'];
        //     // $authorization_mac = cache('authorization_mac');
        //     // if (!$authorization_mac || array_search($mac, $authorization_mac) === false) {
        //     //     cache('Front_' . $authKey, null);
        //     //     header('Content-Type:application/json; charset=utf-8');
        //     //     exit(json_encode(['code' => 105, 'error' => '设备没有授权']));
        //     // }
        //     // 检查账号有效性
        //     $map['id'] = $cache['userInfo']['id'];
        //     $map['status'] = 1;
        //     if (!Db::name('admin_user')->where($map)->value('id')) {
        //         header('Content-Type:application/json; charset=utf-8');
        //         exit(json_encode(['code' => 400, 'error' => '账号已被删除或禁用']));
        //     }
        // }
    }
    /**
     * 设备盒子通过mac检查盒子授权情况
     * 参数
     * mac mac地址 17位数组
     * title 设备名
     */
    public function checkStatusByMac()
    {
        try {
            if (request()->isPost()) {
                $model = Model('equipment');
                if (empty(input('param.mac'))) {
                    return resultArray(['error' => 'mac地址为空']);
                } else if (empty(input('param.title'))) {
                    return resultArray(['error' => '设备名为空']);
                }
                $param = ['mac' => strtoupper(input('param.mac')), 'type' => input('param.type') ?:'1'];
                //授权列表总数
                $authorization_count = $model->where('status', '=', 1)->count();
                //mac地址是否存在
                $result = $model->where($param)->find();
                if (empty($result)) {
                    if ($authorization_count < config('AUTHORIZATION_CEIL')) {
                        //插入新数据，未授权列表
                        $param = [
                            'title' => input('param.title'),
                            'mac' => strtoupper(input('param.mac')),
                            'create_time' => time(),
                            'update_time' => time(),
                            'serial' => input('param.serial') ? 'RS-' . input('param.serial') : "",
                            'type' => input('param.type') ?: '1',
                        ];
                        $id = $model->insertGetId($param);
                        return resultArray(['data' => ['status' => 0, 'id' => $id]]);
                    }
                    return resultArray(['error' => '授权盒子已满', 'code' => 407]);
                } else if ($result['status'] == 0) {
                    //如果有数据但是已授权盒子大于10则返回盒子已满
                    if ($authorization_count >= config('AUTHORIZATION_CEIL')) {
                        return resultArray(['error' => '授权盒子已满', 'code' => 407]);
                    }
                    $id = $result['equipmentid'];
                    $model->updateById(['title' => input('param.title'), 'serial' => input('param.serial') ? 'RS-' . input('param.serial') : "", 'update_time' => time(), 'type' => (input('param.type') ?: 1)], $id);
                } else if ($result['status'] == 1) {
                    $id = $result['equipmentid'];
                    $model->updateById(['title' => input('param.title'), 'serial' => input('param.serial') ? 'RS-' . input('param.serial') : "", 'update_time' => time(), 'type' => (input('param.type') ?: 1)], $id);
                }
                return resultArray(['data' => ['status' => $result['status'], 'id' => $result['equipmentid']]]);
            }
            return resultArray(['error' => '提交错误']);
        } catch (\Exception $e) {
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求错误']);
        }
    }

    /**
     * 设备盒子检查登录情况,并返回服务器储存情况
     * post传递数据
     * 参数
     * username 用户名
     * password 用户密码
     * mac  mac地址
     */
    public function checkLogin()
    {
        if (request()->isPost()) {
            $userModel = Db::name('admin_user');
            $model = Model('equipment');
            $param = input('param.');
            $username = $param['username'];
            $password = $param['password'];
            $mac = strtoupper($param['mac']);
            if (!$username) {
                return resultArray(['error' => '帐号不能为空']);
            }
            if (!$password) {
                return resultArray(['error' => '密码不能为空']);
            }
            $map = [
                'username' => $username,
                'password' => user_md5($password),
            ];

            $user_res = $userModel->where($map)->find();
            if ($user_res['id'] == 1) {
                return resultArray(['error' => '不能用超级管理员登录盒子！']);
            }
            if (!$user_res) {
                return resultArray(['error' => '账号或密码错误']);
            }
            if ($user_res['status'] === 0) {
                return resultArray(['code' => 101, 'error' => '帐号已被禁用']);
            }
            //mac地址是否存在
            if (!$ep_res = $model->get(['mac' => $mac, 'type' => input('param.type') ?:'1'])) {
                //用户是否加入白名单
                if (!$user_res['structure_id']) {
                    $data = [
                        'userId' => '',
                        'username' => '',
                        'status' => 0,
                        'device_id' => '',
                        'token' => '',
                        'type' => '',
                    ];
                    return resultArray(['data' => $data]);
                } else {
                    $param = [
                        'title' => 'default',
                        'mac' => $mac,
                        'create_time' => time(),
                        'update_time' => time(),
                        'serial' => "",
                        'type' => input('param.type') ?: '2',
                        'status' => 1
                    ];
                    $model->data($param)->save();
                    $ep_res = $model;
                }
            } else {
                if (!$ep_res->status) {
                    $data = [
                        'userId' => '',
                        'username' => '',
                        'status' => 0,
                        'device_id' => '',
                        'token' => '',
                        'type' => '',
                    ];
                    return resultArray(['data' => $data]);
                }
            }

            //检查缓存是否有用户登录的信息
            if ($user_res['user_group'] < 18) {
                if (cache('person_' . $user_res['id'])) {
                    $is_set_authkey = cache('person_' . $user_res['id']);
                    if (cache('Front_' . $is_set_authkey)) {
                        cache('Front_' . $is_set_authkey, null);
                    }
                }
            }
            //用户检查通过在这里生成校验的token，同时添加进cache
            //保存缓存        
            session_start();
            $info['userInfo'] = $user_res;
            $info['sessionId'] = session_id();
            $authKey = user_md5($user_res['username'] . $user_res['password'] . $info['sessionId'] . date('Ymd', time()));
            $info['authKey'] = $authKey;
            $info['mac'] = $mac;
            cache('Front_' . $authKey, null);
            cache('Front_' . $authKey, $info, 0);
            cache('person_' . $user_res['id'], $authKey, 0);


            $data = [
                'userId' => $user_res['id'],
                'username' => $username,
                'status' => $ep_res->status ?: 1,
                'device_id' => $ep_res->equipmentid,
                'token' => $authKey,
                'serial' => $ep_res->serial,
                'timestamp' => time(),
                'type' => $ep_res->type,
                'phone' => $user_res['phone'] ?: '',
                'truename' => $user_res['nickname'],
                'wave' => config('huisheng.CAN_WAVE_JEPG') ? ($user_res['post_id'] ?: 2) : 2
            ];
            return resultArray(['data' => $data]);
        }
        return resultArray(['error' => '提交错误']);
    }

    /**
     * 分类登录
     */
    public function typeLogin()
    {
        if (config('huisheng.IS_SN_REGISTER') && $model = Model('UserHasSn')->get(['sn' => input('param.username')])) {
            if (!$model->uid) {
                return $this->snLogin();
            } else {
                return $this->checkLogin();
            }
        } else {
            return $this->checkLogin();
        }
    }

    /**
     * sn号登录验证
     */
    public function snLogin()
    {
        if (request()->isPost()) {
            //判断登录密码
            if (input('param.password') !== '000000') {
                return resultArray(['code' => 401, 'error' => '密码错误']);
            }
            if (!input('param.mac')) {
                return resultArray(['code' => 402, 'error' => '请传入mac地址']);
            }
            $sn_model = Model('UserHasSn')->get(['sn' => input('param.username')]);
            $eq_model = Model('Equipment')->get(['mac' => input('param.mac')]);
            if (!$eq_model) {
                $param = [
                    'title' => input('param.username'),
                    'mac' => input('param.mac'),
                    'create_time' => time(),
                    'update_time' => time(),
                    'serial' => input('param.username'),
                    'type' => input('param.type') ?: '2',
                    'status' => 1
                ];
                $eq_model = Model('Equipment');
                $result = $eq_model->data($param)->save();
                if (!$result) {
                    return resultArray(['code' => 404, 'error' => '插入设备授权出错']);
                }
            } else {
                $param = [
                    'title' => input('param.username'),
                    'update_time' => time(),
                    'serial' => input('param.username'),
                    'type' => input('param.type') ?: '2'
                ];
                $result = $eq_model->save($param);
            }
            $sn_model->eid = $eq_model->equipmentid;
            $sn_model->save();
            return resultArray(['data' => ['status' => 2]]);
        }
        return resultArray(['error' => '提交错误']);
    }

    /**
     * 创建新的用户账户
     */
    public function updateUser()
    {
        try {
            $params = input('param.');
            if (!preg_match('/^[@_.A-Za-z0-9]{6,12}+$/', trim($params['username']))) {
                return resultArray(['error' => '用户名格式错误', 'code' => 401]);
            }
            if (!preg_match('/^[a-zA-Z0-9]{6,12}$/', trim($params['password']))) {
                return resultArray(['error' => '密码格式错误', 'code' => 402]);
            }
            if (!preg_match('/^1[345789]\d{9}$/', trim($params['phone']))) {
                return resultArray(['error' => '手机格式错误', 'code' => 403]);
            }
            if (Model('User')->where(['username' => trim($params['username'])])->find()) {
                return resultArray(['error' => '用户名已存在', 'code' => 404]);
            }
            Db::startTrans();

            $params['status'] = 1;
            $params['structure_id'] = 1;
            $params['user_group'] = 4;
            $params['password'] = user_md5($params['password']);
            $params['nickname'] = $params['nickname'] ?: '';
            $params['create_time'] = time();
            $params['update_time'] = time();

            $user = Model('User');
            $user->data($params)->allowField(true)->save();
            Db::table('rszh_admin_access')->insert(array('user_id' => $user->id, 'group_id' => 4));
            $sn = Model('UserHasSn')->get(['sn' => $params['sn']]);
            if (!$sn) {
                return resultArray(['error' => '录音笔sn不存在', 'code' => 405]);
            }
            if ($sn->uid) {
                return resultArray(['error' => '录音笔sn已绑定用户', 'code' => 406]);
            }
            $sn->uid = $user->id;
            $sn->first_time = time();
            $sn->update_time = time();
            $sn->save();

            //加入sn组
            if ($dep = Model('Department')->get(['title' => 'sn'])) {
                $param = [
                    'did' => $dep->dptid,
                    'uid' => $user->id,
                ];
                Model('GroupUser')->data($param)->save();
            }

            //生成token
            $info['userInfo'] = $user;
            $authKey = user_md5($user->username . $user->password  . date('Ymd', time()));
            $info['authKey'] = $authKey;
            $info['mac'] = $sn->equipment->mac;
            cache('Front_' . $authKey, null);
            cache('Front_' . $authKey, $info, 0);
            cache('person_' . $user->id, $authKey, 0);

            $data = [
                'userId' => $user->id,
                'username' => $user->username,
                'status' => 1,
                'device_id' => $sn->eid,
                'token' => $authKey,
                'serial' => $params['sn'],
                'timestamp' => time(),
                'type' => 2,
                'phone' => $user->phone ?: '',
                'truename' => $user->nickname,
            ];

            Db::commit();
            return resultArray(['data' => $data]);
        } catch (\Exception $e) {
            Db::rollback();
            return resultArray(['error' => '接口错误']);
        }
    }

    /**
     *  获取最近的版本记录数据
     */
    public function getLatestVersion()
    {
        if (empty(input('param.version'))) {
            return resultArray(['error' => '没有参数']);
        }
        $version = input('param.version');
        $model = Model('Version');
        //获取一条最新的数据
        $result = $model->order('version_id desc')->limit(1)->find();
        if (!$result) {
            return resultArray(['error' => '数据不存在，查找失败']);
        }
        $result['status'] = 0;
        if ($result['version'] > $version) {
            $result['status'] = 1;
        }
        return resultArray(['data' => $result]);
    }

    public function updateVersion()
    {
        if (input('param.box_id')) {
            return $this->checkBoxOnVersion();
        } else {
            return $this->checkVersion();
        }
    }

    /**
     * 临时写的检查版本接口
     */
    public function checkVersion()
    {
        $type = input('param.type') ?: 1;
        $result = Model('Version')->where(['device_type' => $type])->order('version_id desc')->limit(1)->find();
        if (!$result) {
            return resultArray(['error' => '数据不存在，查找失败']);
        }
        if (!input('param.versioncode')) {
            $result['status'] = 1;
            return resultArray(['data' => $result]);
        }
        if ($result['code'] > input('param.versioncode')) {
            $result['status'] = 1;
        } else {
            $result['status'] = 0;
        }
        return resultArray(['data' => $result]);
    }

    /**
     *  通过盒子id检查版本记录
     */
    public function getLatestVersionById()
    {
        if (empty(input('param.version')) || empty(input('param.box_id'))) {
            return resultArray(['error' => '没有参数']);
        }
        $version = input('param.version');
        $id = input('param.box_id');
        //更新设备表中的版本号
        $equip_model = Model('Equipment')->get($id);
        $equip_model->version = $version;
        $equip_model->save();
        //判断版本是否小于升级版本
        [$status, $result] = Model('Version')->checkVersion($version);
        if ($status) {
            return resultArray(['data' => $result]);
        }
        //查找是否为强制升级的盒子
        $_model = Model('EquipmentVersion');
        $_result = $_model->get(['eid' => $id, 'vid' => $result['version_id']]);
        if ($_result) {
            $result->is_force = 1;
        }
        return resultArray(['data' => $result]);
    }

    /**
     * 一对一接口
     * 可以使用策略模式改进
     */
    public function checkBoxOnVersion()
    {
        if (!input('param.box_id')) {
            return resultArray(['error' => '参数错误']);
        }
        $type = input('param.type') ?: 1;
        //更新设备表中的版本号
        $equip_model = Model('Equipment')->get(input('param.box_id'));
        $equip_model->version = input('param.version');
        $equip_model->save();
        // if (!input('param.versioncode')) {
        //     //根据type选择更新的版本
        //     $result = Model('Version')->where(['device_type' => $type])->order('version_id desc')->limit(1)->find();
        //     if ($result->is_force) {
        //         return resultArray(['data' => $result]);
        //     }
        //     //查找是否为强制升级的盒子
        //     $_model = Model('EquipmentVersion');
        //     $_result = $_model->get(['eid' => input('param.box_id'), 'vid' => $result['version_id']]);
        //     if ($_result) {
        //         $result->is_force = 1;
        //     }
        //     return resultArray(['data' => $result]);
        // }
        //判断版本是否小于升级版本
        $result = Model('Version')->checkVersionCode(input('param.versioncode'), $type);
        return resultArray(['data' => $result]);
    }

    /**
     * 下载最新版本
     */
    public function downloadVersionFile()
    {
        $filename = input('param.url');
        $path = config('huisheng.package_upload_path') . DS . $filename;
        if (is_file($path)) {
            download_result_one($path);
        } else {
            return resultArray(['error' => '文件不存在']);
        }
    }

    /**
     * 修改设备名
     * @device_id   设备id  
     * @title       设备新名字 
     */
    public function deviceNameUpdate()
    {
        $id = input('param.device_id');
        if (!isset($id) || empty($id)) {
            return resultArray(['error' => '设备id不能为空']);
        }
        $title = input('param.title');
        if (!isset($title) || empty($title)) {
            return resultArray(['error' => '设备名不能为空']);
        }
        try {
            //更新equipment表中的数据
            $equip = Model('Equipment');
            $result = $equip->updateById(['title' => $title, 'update_time' => time()], $id);
            if (!$result) {
                return resultArray(['error' => '更新失败']);
            }
        } catch (\Exception $e) {
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求错误']);
        }
        return resultArray(['data' => '']);
    }

    /**
     * 检查服务器状态
     * 
     */
    public function checkServerState()
    {
        try {
            //硬盘剩余容量
            $df = round(@disk_free_space(".") / (1024 * 1024 * 1024), 3);
            //硬盘总容量，web服务器目录所在磁盘的空间，最好服务器只有一个硬盘
            $dt = round(@disk_total_space(".") / (1024 * 1024 * 1024), 3);
            //磁盘使用占比
            $percent = (floatval($dt) != 0) ? round((($dt - $df) / $dt) * 100, 2) : 0;
            //判断磁盘是否预警
            switch (floor($percent / 10)) {
                case '8':
                    $status = 1;
                    break;
                case '9':
                    $status = 2;
                    break;
                default:
                    $status = 0;
                    break;
            }
            $data = [
                'status' => $status,
            ];
            return resultArray(['data' => $data]);
        } catch (\Exception $e) {
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求错误']);
        }
    }


    /**
     * 转写开始接口
     * 创建实时转写文件数据
     * @device_id   设备id
     * @user_id     用户id
     * @meeting_id  会议id
     * @start_time  会已转写开始时间
     */
    public function transferStart($meeting_id = '', $start_time, $device_id = 0, $user_id = 0, $file_name = '', $manual = 1, $scene = 1, $title = '')
    {
        try {
            //如果没有会议id 自动生成一个
            if (empty($meeting_id) || !isset($meeting_id)) {
                $meeting_id = "z-0-" . time();
            }
            //如果没有转写开始时间 自动生成一个
            if (empty($start_time) || !isset($start_time)) {
                $start_time = time();
            }

            $equipment = Model('Equipment')->get($device_id);
            $param = [
                'uid' => $user_id,
                'did' => $device_id,
                'meeting_tag' => $meeting_id,
                'filename' => $file_name,
                'formatname' => md5(time() . $user_id . $device_id),
                'start_time' => strtotime($start_time),
                'create_time' => time(),
                'update_time' => time(),
                'transfer' => '',
                'editor' => '',
                'is_manual' => $manual,
                'transition_state' => 4,
                'sid' => $scene,
                'title' => $title,
            ];

            //创建实时转写模型类
            $live = Model('LiveSpeech1');

            //插入数据
            $live->createData($param);
            //获取id
            $lid = $live->get(['meeting_tag' => $meeting_id])->id;

            $result = [
                'fileid' => $lid,
            ];
            return resultArray(['data' => $result]);
        } catch (\Exception $e) {
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求错误']);
        }
    }

    private function speechDetailCreate($lid)
    {
        $liveDetailModel = Model('LiveDetail');
        $param = [
            'lid' => $lid,
        ];
        $liveDetailModel->createData($param);
    }

    // private function updateStatus($live, $manual){
    //     $live->transition_state = 1;
    //     $live->is_manual = $manual;
    //     $live->save();
    //     return resultArray(['data' => $result]);
    // }

    /**
     * 转写结束接口 
     * 
     * 修改实时转写数据
     * @meeting_id  会议id
     * @end_time  会已转写开始时间
     */
    public function transferEnd()
    {
        try {
            //更新数据库数据库
            if (input('param.id')) {
                $id = input('param.id');
                $live = Db::name('meeting_live_speech')->where('id', $id)->find();
                if (!$live) {
                    return resultArray(['error' => '没有结果']);
                }
                $result = Db::name('meeting_live_speech')->where(['transition_state'=>4,'id'=>$id])->update(['transition_state' => 5]);
                if($result){
                    $arr = [
                        'id' => $id
                    ];
                    self::$redis->mergeQueuePush($arr);
                }
                return resultArray(['data' => '']);
            }else{
                return resultArray(['error' => '参数错误']);
            }

        } catch (\Exception $e) {
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求错误']);
        }
    }

    /**
     * 获取非实时 
     * 
     * 修改实时转写数据
     * @meeting_id  会议id
     * @end_time  会已转写开始时间
     */
    public function NoneRealTimeResult($id, $type = 1)
    {
        try {
            //判断参数是否为空
            if (empty($id)) {
                return resultArray(['error' => '会议id为空']);
            }
            //查询数据
            //$_status = DB::name('meeting_live_speech')->where(['id' => $id])->field('id,transition_state,transfer,is_manual')->find();
            $result = Model('LiveSpeech1')->getDetail($this->param['id'], 1);
            //var_dump($result);die;
            $lvsr_data = $result['lvsr_data'];
            //文本换行处理
            $transcriptResult = '';
            $transArr = [];
            foreach ($lvsr_data as $k => $v) {
                if (!isset($transArr[$v['sc']])) {
                    $transArr[$v['sc']]['sc'] = $v['sc'];
                    $transArr[$v['sc']]['txt'] = '';
                }
                $transArr[$v['sc']]['txt'] .= trim($v['txt']);
                $transcriptResult .= $lvsr_data[$k]['txt'];
            }
            $data = [
                'transcriptResult' => $transcriptResult,
                'transArr' => $transArr,
                'transferState' => ($result['status'] == 2 || $result['status'] == 5) ? 1 : 0,
                'endTime' => time(),
                'type' => $result['is_manual']
            ];
            return resultArray(['data' => $data]);
        } catch (\Exception $e) {
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求错误']);
        }
    }

    /**
     * 上传音频文件（废弃）
     */
    public function uploadAudioFile($filename, $path, $device_id = 0, $user_id = 0)
    {
        try {
            //如果没有会议id 自动生成一个
            if (!$filename) {
                return resultArray(['error' => '文件名不能为空']);
            }
            $path_arr = explode("/", $path);
            $username = Model('User')->get($path_arr[2])->username;
            $file = config('huisheng.base_dir') . "/ftp/$path/$filename";
            $formatname = (md5(uniqid($user_id)));

            $param = [
                'uid' => $user_id,
                'did' => $device_id,
                'meeting_tag' => "$username-" . $path_arr[1] . "-" . $path_arr[3],
                'filename' => $filename,
                'formatname' => $formatname,
                'start_time' => time(),
                'create_time' => time(),
                'update_time' => time(),
                'is_manual' => 2,
                'transfer' => '',
                'editor' => '',
            ];
            //创建实时转写模型类
            $live = Model('LiveSpeech1');
            //插入数据
            $result_id = $live->createFileData($param);
            if (!$result_id) {
                return resultArray(['error' => $live->getError()]);
            }

            //插入另一个表
            $params = [
                'device_id' => $device_id,
                'filename' => $filename,
                'user_id' => $user_id,
                'formatname' => pathinfo($formatname)['filename'] . ".wav",
                'create_time' => time(),
                'update_time' => time(),
                'lvsr_status' => 0
            ];
            $res = $live->oneSpeech()->save($params);
            if (!$res) {
                return resultArray(['error' => $live->getError()]);
            }

            $push_array = [
                'id' => $result_id,
                'ori_path' => $file,
                'des_path' => config('huisheng.box_audio_dir') . DS . pathinfo($formatname)['filename'] . ".wav",
            ];
            self::$redis->pushUploadFileQueue($push_array);
            return resultArray(['data' => '']);
        } catch (\Exception $e) {
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求错误']);
        }
    }

    //根据转写id修改转写结果（废弃）
    public function updatePiece()
    {
        try {
            $param = input('param.');
            //如果没有会议id 自动生成一个
            if (!$param['mid']) {
                return resultArray(['error' => '会议id为空']);
            }
            if (!isset($param['sid'])) {
                return resultArray(['error' => '转写id为空']);
            }
            $speech = Model('LiveSpeech1')->get($param['mid']);
            $result = $speech->mconvert()->where('sorting', $param['sid'] + 1)->update(['editor' => $param['content'] ?: '']);
            $speech->edit_state = 1;
            $speech->save();
            return resultArray(['data' => '']);
        } catch (\Exception $e) {
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求错误']);
        }
    }


    public function downZipFile()
    {
        $param = input('param.');
        //先屏蔽用户id
        //$cache = cache('Front_' . $param['token']);
        //$map['uid'] = $cache['userInfo']['id'];
        if (!$param['id']) {
            return json("File Not Found", 404);
        }
        // $map = [
        //     'did' => Model('Equipment')->get(['mac' => $param['address']])->equipmentid,
        //     'filename' => $param['file_name'],
        // ];
        $file = Model('LiveSpeech1')->where('id', $param['id'])->find();
        $zip_path = config('huisheng.word_result') . DS . $file->formatname . '.zip';
        if (!file_exists($zip_path)) {
            //生成下载文件
            $args = ['title' => '', 'time' => '', 'address' => '', 'host' => '', 'record' => '', 'name' => '', 'remark' => '', 'data' => ''];
            $doc_path = $file->getDownloadFile($file->id, 'doc', $args);
            $mp3_path = $file->getDownloadFile($file->id, 'mp3', $args);
            $zip_file['names'] = $param['file_name'];
            $zip_file['mp3'][] = $mp3_path;
            $zip_file['docx'][] = $doc_path;
            download_result_e($zip_path, $zip_file);
            exit;
        } else {
            download_result_one($zip_path);
        }
    }

    /**
     * 新接口 获取用户设备非实时录音列表
     */
    public function list()
    {
        $param = input('param.');
        $result = Db::name('meeting_live_speech')
            ->where(['uid' => $param['user_id'], 'did' => $param['device_id']])
            ->field('id,transition_state as status, filename, is_manual as manual')->select();
        return resultArray(['data' => ['list' => $result, 'count' => count($result)]]);
    }

    /**
     * 修改密码
     */
    public function changePassword($token, $old_pwd, $new_pwd)
    {
        $param = input('param.');
        if(isset($param['uid'])){
            $token = cache('person_' . input('param.uid'));
        }
        $user = Model('User');
        $result = $user->setPasswd($token, $old_pwd, $new_pwd);
        if (!$result) {
            return resultArray(['error' => $user->getError()]);
        }
        return resultArray(['data' => ['token' => $result]]);
    }

    /**
     * 修改个人信息
     */
    public function updateUserInfo()
    {
        $param = input('param.');
        $user = Model('User');
        $token = $param['token'];
        if ($userinfo = cache('Front_' . $token)) {
            $id = $userinfo['userInfo']->id?:$userinfo['userInfo']['id'];
        } else if(isset($param['uid'])){
            $id = $param['uid'];
        } else {
            return resultArray(['error' => 'token错误']);
        }
        unset($param['uid']);
        if ($param['phone']) {
            if (!preg_match('/^1[345789]\d{9}$/', trim($param['phone']))) {
                return resultArray(['error' => '手机格式错误']);
            }
        }
        $result = $user->updateDataById($param, $id);
        if (!$result) {
            return resultArray(['error' => $user->getError()]);
        }
        return resultArray(['data' => '']);
    }

    /**
     * 修改文件信息
     */
    public function updateFileInfo()
    {
        $param = input('param.');
        $speech = Model('LiveSpeech1');
        if (!$param['id']) {
            return resultArray(['error' => '参数错误']);
        }
        $result = $speech->updateDataById($param, $param['id']);
        if (!$result) {
            return resultArray(['error' => $speech->getError()]);
        }
        return resultArray(['data' => '']);
    }

    //获取文件非实时转写结果
    public function getSpeechResult()
    {
        try {
            $param = input('param.');
            $data = [
                'status' => 2,
                'type' => 1
            ];
            $live_model = Db::name('meeting_live_speech')->where(['id' => $param['fileid']])->find();
            if ($live_model['transition_state'] == 2) {
                $data['result'] = json_decode($live_model['transfer'], true);
                $data['create_time'] = $live_model['create_time'];
                $data['update_time'] = $live_model['update_time'];
                $data['status'] = 1;
            }
            return resultArray(['data' => $data]);
        } catch (\Exception $e) {
            $data['status'] = 3;
            //$data['message'] = $e->getMessage();
            $data['message'] = '请求失败';
            return resultArray(['data' => $data]);
        }
    }

    //文件列表状态
    public function transFileList($file_id = []){
        $result = Db::name('meeting_live_speech')->where('id', 'in', json_decode($file_id,true))->field('id,transition_state as status,is_manual as manual')->select();
        return resultArray(['data' => ['list' => $result, 'count' => count($result)]]);
    }

    /**
     * 获取反馈信息接口
     */
    public function suggestion($user_id=0,$type='',$describe,$phone)
    {
        try {
            $field = [
                'uid' => $user_id,
                'type' => $type,
                'describe' => $describe,
                'phone' => $phone,
                'create_time' => time(),
                'update_time' => time(),
            ];
            $result_id = Db::name('suggestion')->insertGetId($field);

            $content =  "问题类型：" . $type . "\r\n<br>" . "问题描述：" . $describe . "\r\n<br>" . "联系方式：" . $phone;
            $data = [
                'title' => '意见反馈',
                'send_email' => 'asrupload@raisound.com',
                'content' => $content
            ];
            //发送邮件
            sendEmail($data);
            return resultArray(['data' => ['status' => 1,'message' => '发送成功']]);
        } catch (\Exception $e) {
            Db::name('suggestion')->where(['id'=>$result_id])->update(['status' => 2]);
            return resultArray(['data' => ['status' => 2,'message' => '发送失败']]);
        }
    }
}
